/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.dao {
	
	import com.adobe.net.URI;
	import com.cred.industries.platform.business.object.CustomerBO;
	import com.cred.industries.platform.dao.event.CustomerDAOEvent;
	import com.cred.industries.platform.transferobj.CustomerListTrans;
	import com.googlecode.flexxb.FlexXBEngine;
	
	import flash.events.ErrorEvent;
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	
	import mx.messaging.channels.StreamingAMFChannel;
	
	import org.httpclient.HttpClient;
	import org.httpclient.HttpRequest;
	import org.httpclient.events.HttpDataListener;
	import org.httpclient.events.HttpResponseEvent;
	import org.httpclient.events.HttpStatusEvent;
	import org.httpclient.http.Get;
	import org.httpclient.http.Post;
	
	[Event(name="CUSTOMER_CREATED", type="com.cred.industries.dao.event.CustomerDAOEvent")]
	[Event(name="CUSTOMER_UPDATE", type="com.cred.industries.dao.event.CustomerDAOEvent")]
	[Event(name="CUSTOMER_GET_ONE", type="com.cred.industries.dao.event.CustomerDAOEvent")]  
	[Event(name="CUSTOMER_GET_GROUP", type="com.cred.industries.dao.event.CustomerDAOEvent")]
	[Event(name="CUSTOMER_FAILED", type="com.cred.industries.dao.event.CustomerDAOEvent")]  
	
	/**
	 * @author Colin Redmond
	 * Copyright 2011
	 **/
	public final class CustomerDAO extends EventDispatcher {
		
		private static var mCustomerPath:String = "customer"
		private static var mCreatepath:String = "create";
		private static var mFindByPersonaName:String = "group"; 
		private var mStatusCode:int = 0;
		private var mData:ByteArray = null;
		public function CustomerDAO() { }
		
		public function createCustomer(customer:CustomerBO):void {
			
			var client:HttpClient = new HttpClient();
		
			var listener:HttpDataListener = new HttpDataListener();
			listener.onStatus = statusHandler;
			listener.onDataComplete =  dataCompleteHandler;
			listener.onComplete = createCompleteHandler;
			listener.onError = errorHandler;
			client.listener = listener;
			
			var uri:URI = new URI(ServerDAODefines.serverURL +  mCustomerPath + "/" + mCreatepath);
			
			var custXML:XML = FlexXBEngine.instance.serialize(customer);
			var request:HttpRequest = new Post();
			request.contentType = "application/xml";
			var XMLHeader:String = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> \n";
			var XMLBody:String = XMLHeader  + custXML.toXMLString();
			
			var body:ByteArray = new ByteArray();
			body.writeUTFBytes(XMLBody);
			body.position = 0;
			request.body = body;

			client.request(uri, request);
		}
		
		public function findCustomerByPersonaName(sessionKey:String, persona:String):void {
			
			var client:HttpClient = new HttpClient();
			
			var listener:HttpDataListener = new HttpDataListener();
			listener.onStatus = statusHandler;
			listener.onDataComplete =  dataCompleteHandler;
			listener.onComplete = findCompleteHandler;
			listener.onError = errorHandler;
			client.listener = listener;
			
			var uri:URI = new URI(ServerDAODefines.serverURL +  mCustomerPath + "/" + mFindByPersonaName + "/" + persona);
			var request:HttpRequest = new Get();
			request.contentType = "text/plain";
			request.addHeader("sessionid", sessionKey);
			request.addHeader("Accept", "application/xml");

			client.request(uri, request);
		}
		
		public function FindCustNextOrPrev(sessionKey:String, url:String):void {
			
			var client:HttpClient = new HttpClient();
			
			var listener:HttpDataListener = new HttpDataListener();
			listener.onStatus = statusHandler;
			listener.onDataComplete =  dataCompleteHandler;
			listener.onComplete = findCompleteHandler;
			listener.onError = errorHandler;
			client.listener = listener;
			
			var uri:URI = new URI(url);
			var request:HttpRequest = new Get();
			request.contentType = "text/plain";
			request.addHeader("sessionid", sessionKey);
			request.addHeader("Accept", "application/xml");
			
			client.request(uri, request);
		}
		
		private function createCompleteHandler(event:HttpResponseEvent):void {
			
			if(mStatusCode == 200 || mStatusCode == 201)
				dispatchEvent(new CustomerDAOEvent(CustomerDAOEvent.CUSTOMER_CREATED));
			else
				dispatchEvent(new CustomerDAOEvent(CustomerDAOEvent.CUSTOMER_FAILED, null, mData.toString()));
		}
		
		private function findCompleteHandler(event:HttpResponseEvent):void {
			
			if(mStatusCode == 200 || mStatusCode == 201)
			{
				var dataXML:XML = new XML(mData);
				var custList:CustomerListTrans = FlexXBEngine.instance.deserialize(dataXML, CustomerListTrans) as CustomerListTrans;
				dispatchEvent(new CustomerDAOEvent(CustomerDAOEvent.CUSTOMER_GET_GROUP, custList));
			}
			else
				dispatchEvent(new CustomerDAOEvent(CustomerDAOEvent.CUSTOMER_FAILED, null, mData.toString()));
		}
		
		private function errorHandler(event:ErrorEvent):void {
			
			trace( "CustomerDAO Had problem connecting. " + event.toString() );
			dispatchEvent(new CustomerDAOEvent(CustomerDAOEvent.CUSTOMER_FAILED, null, "Server did not respond. Please have the server administrator check the server"));
		}
		
		private function dataCompleteHandler(event:HttpResponseEvent, data:ByteArray):void {
			
			trace("CustomerDAO data " + data.toString());
			mData = data;
		}
		
		private function statusHandler(event:HttpStatusEvent):void {
			
			trace("CustomerDAO HTTPStatusEvent " + event.response.code); 
			mStatusCode = int(event.response.code);
		}
	}
}